﻿using Duende.IdentityServer.Validation;
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Simple.ISysService;
using Simple.Tools;
using SimpleSaas.Common;
using SimpleSaas.Entity.Dto;
using SimpleSaas.Web.Common.redis;
using System.DirectoryServices;
using System.Security.Claims;

namespace SimpleSaasAuth.Services
{
	public class UserVerifyService : IUserVerifyService
	{

		[Autowired]
		private ISystemClock clock { get; set; }
		[Autowired]
		private ISysUserService sysUserService { get; set; }

		[Autowired]
		private IRedisClientService redisClientService { get; set; }

		[Autowired]
		private ILogger<UserVerifyService> logger { get; set; }
		/// <summary>
		/// 
		/// </summary>
		public UserVerifyService()
		{
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="loginUserDto"></param>
		/// <param name="errorMsg"></param>
		/// <returns></returns>
		public async Task<GrantValidationResult> LoginAsync(LoginUserDto loginUserDto, string errorMsg = "")
		{
			LoginUserInfo userInfo = new LoginUserInfo();
			List<Claim> claims = new List<Claim>();
			#region 账号合法性验证
			try
			{
				switch (loginUserDto.AuthenticateType)
				{
					case 1:
						userInfo = await sysUserService.LoginByPasswordAsync(loginUserDto);
						if (SimpleCheck.IsNotNull(userInfo))
						{
						}
						else
						{
							return GetGrantValidationResult(false, errorMsg);
						}
						break;
					default:
						break;
				}
				#endregion

				#region 重复登录达到最大值再次登录提示信息

				#endregion

				#region 


				#endregion

				#region token中存储的信息
				claims.Add(new Claim(ClaimTypes.NameIdentifier, userInfo.UserId.ToString()));
				claims.Add(new Claim(ClaimTypes.Name, userInfo.UserName));
				claims.Add(new Claim("phoneNumber", userInfo.PhoneNumber));
				claims.Add(new Claim("tenantId", userInfo.TenantId.ToString()));
				claims.Add(new Claim("tenantName", userInfo.TenantName.ToString()));
				claims.Add(new Claim("databaseId", userInfo.DatabaseId.ToString()));
				#endregion

				return GetGrantValidationResult(false, "token授权成功!", userInfo.UserId.ToString(), claims);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.Message);
				logger.LogError(ex.StackTrace);
				return GetGrantValidationResult(true, "服务器异常!", userInfo.UserId.ToString(), claims);
			}

		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="IsError"></param>
		/// <param name="msg"></param>
		/// <param name="userId"></param>
		/// <param name="claims"></param>
		/// <returns></returns>
		private GrantValidationResult GetGrantValidationResult(bool IsError, string msg = "", string userId = "", List<Claim> claims = null)
		{
			Dictionary<string, object> customeResponse = new Dictionary<string, object>();
			customeResponse.Add("msg", msg);
			GrantValidationResult GrantValidationResult;
			if (IsError)
			{
				customeResponse.Add("code", 400);
				GrantValidationResult = new GrantValidationResult(
					"",
					OidcConstants.AuthenticationMethods.Password,
					null, "",
					customeResponse);
			}
			else
			{
				customeResponse.Add("code", 200);
				GrantValidationResult = new GrantValidationResult(
												userId,
												 OidcConstants.AuthenticationMethods.Password,
												 this.clock.UtcNow.UtcDateTime,
												 claims, "local", customeResponse);
			}
			return GrantValidationResult;
		}
	}
}